# -*- coding: utf-8 -*-
# File : novc_plot.py
# Author: taoyahui
# Date : 2022/6/8

import json
import requests
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
api_key = '3b69725737f6f37409ad77d7ba648c6c'
if __name__ == '__main__':
    # 字典，键为国家名，值为确诊人数列表。
    nations = {'美国': [], '意大利': [], '德国': []} # key值为国家名，value是新冠确诊人数
    # 加入获取的时间偏移天数
    delta_time = 7

    #时间列表
    date_list = []
    start_date = datetime.now().strftime('%Y-%m-%d')
    for i in range(delta_time):
        date_info = (datetime.strptime(start_date, '%Y-%m-%d') + timedelta(-int(i))).strftime('%Y-%m-%d')
        url = "http://api.tianapi.com/txapi/ncovabroad/index?key={}&date={}".format(api_key, date_info)
        ret = requests.get(url)
        # 只能说明主机响应了，但数据也许有问题
        if ret.status_code == 200:
            text = json.loads(ret.text)
            # 要判断是不是正确的请求到了数据
            try:
                if text['code'] == 200:
                    date_list.append(date_info)
                    newslist = text['newslist']
                    for news in newslist:
                        for nation in nations:
                            if news['provinceName'] == nation:
                                nations[nation].append((news['confirmedCount']))
            except Exception as exc:
                print(exc)
    # 将确诊人数反转，离现在远的在前，离现在近的在后。
    for k, v in nations.items():
        v.reverse()
    date_list.reverse()
    print(date_list)
    print(nations)

    plt.rcParams['font.sans-serif'] = ['SimHei']

    # 设置图像的标题
    plt.title("一周疫情图", fontsize='xx-large')

    # 设置图例
    marker_list = ['p', 'D', 'd']

    # 设置图像颜色
    color_list = ['r', 'g', 'b']

    plt.xlabel('时间', fontsize='large')
    plt.ylabel("累计确诊人数", fontsize='large')

    for i, v in enumerate(nations.keys()):
        plt.plot(date_list, nations[v], color=color_list[i], marker=marker_list[i], markersize=10, label=v)
        plt.legend(loc="best", fontsize='x-large')
    plt.show()
    plt.close()


